//
//  SimilarPicViewController.m
//  安好
//
//  Created by rlp on 14-12-9.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "SimilarPicViewController.h"



@interface TestData : NSObject

@property (nonatomic,strong) UIColor *color;
@property (nonatomic,assign) CGFloat height;
@property (nonatomic,strong) NSString *strImage;


@end

@implementation TestData

@end
@interface SimilarPicViewController ()

@end

@implementation SimilarPicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 1;
    if (!self.imageUrls) {
        self.imageUrls =[[NSMutableArray alloc]initWithCapacity:10];

    }
    if (!self.dataArrayTitle) {
        self.dataArrayTitle=[[NSMutableArray alloc]initWithCapacity:10];
        
    }
    if (!self.dataArrayUrl) {
        self.dataArrayUrl=[[NSMutableArray alloc]initWithCapacity:10];
        
    }
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout=UIRectEdgeNone;
    

    [self makeNavBarView];
    [self makeTableView];

}
#pragma mark - 创建ZBWaterView 
-(void)makeTableView
{
    self.waterView = [[ZBWaterView alloc]  initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)];
    self.waterView.waterDataSource = self;
    self.waterView.waterDelegate = self;
    self.waterView.isDataEnd = NO;
    [self.view addSubview:self.waterView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - 设置导航条
-(void)makeNavBarView
{
    self.title = @"相似图片";
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
    [rightButton setImage:[UIImage imageNamed:@"公用_相机"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    [self rightButtonClicked:nil];
}

-(void)leftButtonClicked:(UIButton *)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)rightButtonClicked:(UIButton *)sender{
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:@"选择相册",@"摄像头选取",@"取消", nil];
    alert.delegate = self;
    alert.tag = 0;
    [alert show];
}
#pragma mark - alertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 0) {
        switch (buttonIndex) {
            case 0:
                [self library];
                break;
            case 1:
                [self camera];
                break;
            default:
                [self.navigationController popViewControllerAnimated:YES];
                break;
        }
    }
}
//本地相册获取图片
- (void)library
{
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc]init];
    
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePickerController.allowsEditing = YES;
    
    
    [self presentViewController:imagePickerController animated:YES completion:nil];
}
//调用相机拍照
- (void)camera
{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc]init];
        
        imagePickerController.delegate = self;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePickerController.allowsEditing = YES;
        
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else{
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"您好，你的手机不支持摄像功能" delegate:self cancelButtonTitle:nil otherButtonTitles:@"取消", nil];
        alert.delegate = self;
        alert.tag = 10;
        [alert show];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    
//    [self loadDataWithDictonary:info];
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]) {
        [self loadDataWithDictonary:info];
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
    //如果进入相册后选择了取消就直接 回到上级界面
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - post图片获得相似的图片
- (void)loadDataWithDictonary:(NSDictionary *)dict
{

    
    
    UIImage *postImage = [dict objectForKey:UIImagePickerControllerEditedImage];
    
    
    
    
    [self showActionView];
    NSData* imageData = UIImageJPEGRepresentation(postImage, 0.5);
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@shitu/upload/",kBaseURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"george.jpg" mimeType:@"image/jpeg"];
        
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [self hiddenActionView];
        if (error) {
            MyNSLog("Error: %@", error);
        } else {
            self.signString = [[responseObject objectForKey:@"data"] objectForKey:@"sign"];

            //图片上传成功
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"]) {
                self.page=1;
                [self.imageUrls removeAllObjects];
                [self.dataArrayTitle removeAllObjects];
                [self.dataArrayUrl removeAllObjects];
                NSMutableArray *dataArray = [[responseObject objectForKey:@"data"] objectForKey:@"data"];
                for(NSDictionary *subDict in dataArray)
                {
                    [self.dataArrayUrl addObject:[subDict objectForKey:@"url"]];
                    [self.dataArrayTitle addObject:[subDict objectForKey:@"alt"]];
                    [self.imageUrls addObject:[subDict objectForKey:@"imgurl"]];
//                    [self.baseCArray addObject:[subDict objectForKey:@"url"]];
                }

                [self.waterView reloadData];
                
                
            }else
            {
                
            }
        }
    }];
    [uploadTask resume];
    
 }
- (void)loadData
{

    
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)self.page] forKey:@"n"];
    [dict setObject:self.signString forKey:@"sign"];
       AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,@"/shitu/similarpic/"] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
        MyNSLog("%@",responseObject);
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];//失败
        }else{
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                self.signString = [[responseObject objectForKey:@"data"] objectForKey:@"sign"];
                
                NSMutableArray *dataArray = [[responseObject objectForKey:@"data"] objectForKey:@"data"];
                for(NSDictionary *subDict in dataArray)
                {
                    [self.dataArrayUrl addObject:[subDict objectForKey:@"url"]];
                    [self.dataArrayTitle addObject:[subDict objectForKey:@"alt"]];
                    [self.imageUrls addObject:[subDict objectForKey:@"imgurl"]];
//                    [self.baseCArray addObject:[subDict objectForKey:@"url"]];
                }

                
                
                
                if ([[responseObject objectForKey:@"data"] count]>0) {
                    self.page ++;
                }else{
                
                }
                [self.waterView endLoadMore];
                [self.waterView reloadData];
        
            }else{
                [self showCustomHudSingleLine:@"网络数据格式错误"];
            }
            
        }
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        
    }];


    

    
}

#pragma mark - ZBWaterViewDatasource
- (NSInteger)numberOfFlowViewInWaterView:(ZBWaterView *)waterView
{
    return [self.dataArrayUrl count];
}

- (CustomWaterInfo *)infoOfWaterView:(ZBWaterView*)waterView
{
    CustomWaterInfo *info = [[CustomWaterInfo alloc] init];
    info.topMargin = 0;
    info.leftMargin = 10;
    info.bottomMargin = 0;
    info.rightMargin = 10;
    info.horizonPadding = 5;
    info.veticalPadding = 5;
    info.numOfColumn = 2;
    return info;
}

- (ZBFlowView *)waterView:(ZBWaterView *)waterView flowViewAtIndex:(NSInteger)index
{
    
    
    
    
    
    
    TestData *data = [self.testDataArr objectAtIndex:index];
    ZBFlowView *flowView = [waterView dequeueReusableCellWithIdentifier:@"cell"];
//    if (flowView == nil) {
        flowView = [[ZBFlowView alloc] initWithFrame:CGRectZero];
        flowView.reuseIdentifier = @"cell";

//    }
    
    flowView.index = index;
    flowView.backgroundColor = data.color;
    [flowView setImageURLStr:[self.imageUrls objectAtIndex:index] placeholder:nil];
    flowView.userInteractionEnabled = YES;
    flowView.textLabel.text =  [self.dataArrayTitle objectAtIndex:index];
    flowView.textLabel.tag = index+LABEL_TAG_ADD;

    MyNSLog("flowView.height=%f",flowView.height);

    

    
    return flowView;
}

- (CGFloat)waterView:(ZBWaterView *)waterView heightOfFlowViewAtIndex:(NSInteger)index
{

return arc4random()%200+100;
  
}


#pragma mark - ZBWaterViewDelegate
- (void)needLoadMoreByWaterView:(ZBWaterView *)waterView;
{

    [self loadData];
}

- (void)phoneWaterViewDidScroll:(ZBWaterView *)waterView
{
    //do what you want to do
    return;
}
- (void)waterView:(ZBWaterView *)waterView didSelectAtIndex:(NSInteger)index FlowViewlabel:(UILabel *)flowViewlabel{

    PicWebViewController *picWebView = [[PicWebViewController alloc] init];
    picWebView.url = [self.dataArrayUrl objectAtIndex:flowViewlabel.tag - LABEL_TAG_ADD];
    picWebView.title = [self.dataArrayTitle objectAtIndex:flowViewlabel.tag - LABEL_TAG_ADD];
    [self.navigationController pushViewController:picWebView animated:YES];

}
- (void)waterView:(ZBWaterView *)waterView didSelectAtIndex:(NSInteger)index
{
    MyNSLog("didSelectAtIndex%ld",(long)index);

}

- (void)waterView:(ZBWaterView *)waterView didSelectAtIndex:(NSInteger)index FlowView:(ZBFlowView *)flowView{
    NSMutableArray *arrimages = [[NSMutableArray alloc ]initWithObjects:[self.imageUrls objectAtIndex:index], nil];
    NSInteger count = arrimages.count;
    // 1.封装图片数据
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++) {
        // 替换为中等尺寸图片
//        NSString *url = arrimages[i];
        MJPhoto *photo = [[MJPhoto alloc] init];
        NSString *url =nil;
        NSRange range;
        range = [arrimages[i] rangeOfString:@"@"];
        if (range.location != NSNotFound) {
            url = [arrimages[i] substringToIndex:range.location];
        }else{
            url = arrimages[i];
        }
        photo.url = [NSURL URLWithString:url]; // 图片路径
        photo.srcImageView = flowView; // 来源于哪个UIImageView
        [photos addObject:photo];
    }
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = 0; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}



@end
